import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { StyleSheet } from 'react-native';
import {
  List,
  SearchBar,
  Tag,
  Checkbox,
  Button,
  Toast,
  Flex,
  Picker,
} from '@ant-design/react-native';
import { LoadingContainer } from '@/rcomponents/Container';
import ClosableTag from '@/rcomponents/closableTag';
import { IconX } from '@/rcomponents/iconx';
import UserStore from '@/stores/userStore';
import ReleaseJobStore from './releaseJobStore';
import { TouchableOpacity } from 'react-native-gesture-handler';

const styles = StyleSheet.create({
  searchbarSty: { height: 40, fontSize: 16 },
});

const MemoizedRenderItem = React.memo(
  ({ item, onUserCheck }) => {
    const [localUser, setLocalUser] = useState(item);
    useEffect(() => {
      //console.log('local, user render checked');
      if (item.checked !== undefined && item.checked !== localUser.checked) {
        setLocalUser(item);
      }
    }, [item.checked]);
    const handleCheck = (ev) => {
      const newItem = { ...item, checked: ev.target.checked };
      setLocalUser(newItem);
      onUserCheck(newItem);
    };
    const str = `${item.name}  (${item.teamName} / ${item.stationCode})`;
    return (
      <Checkbox.CheckboxItem checked={localUser.checked} onChange={handleCheck}>
        {str}
      </Checkbox.CheckboxItem>
    );
  },
  (prevProps, nextProps) => {
    return prevProps.item.checked === nextProps.item.checked;
  },
);

function WorkerUserSelectPage({ navigation, route }) {
  const userStore = UserStore.useStore();
  const rjStore = ReleaseJobStore.useStore();
  const [searchVal, setSearchVal] = useState('');
  const [deptPicks, setDeptPicks] = useState([]);
  const [assigning, setAssigning] = useState(false);
  let didUnmount = false;
  useEffect(() => {
    handleLoadWorkerUsers();
    navigation.setOptions({
      title: route.params.title || '选择人员',
    });
    return () => {
      userStore.clearFlightWorkers();
      didUnmount = true;
    };
  }, [route.params]); // { taskTid: [], title, type, acno, ifMain taskstagetid flightTid }
  const handleLoadWorkerUsers = async () => {
    if (route.params && route.params.type) {
      const acnoUserSearch = {
        type: route.params.type, // 1（放行人员），2 （有授权的技术员），3 (学员)，4 (工作者)，
        acno: route.params.acno,
      };
      const taskMainSearch = {
        taskStageTid: route.params.taskTid.join(','),
        ifMain: route.params.ifMain,
      };
      await userStore.getFlightWorkerUsers(acnoUserSearch, taskMainSearch);
    }
  };
  const handleSearchCancel = () => {
    setSearchVal('');
  };
  const handleSearchChange = (val) => {
    setSearchVal(val);
  };
  const handleUserCheck = useCallback((suser) => {
    userStore.setFlightWorker(suser);
  }, []);
  const handleDeptPick = (val) => {
    setDeptPicks(val);
  };
  const selectedUsers = userStore.flightWorkers.workers.filter(
    (fwd) => fwd.checked,
  );
  const handleUserAssign = async () => {
    setAssigning(true);
    if (route.params.type) {
      const setPara = {
        taskTid: route.params.taskTid.join(','),
        taskStageTid: route.params.taskStageTid,
        flightTid: route.params.flightTid,
        selectUserId: selectedUsers.map((fwd) => fwd.id).join(','),
        ifMain: route.params.ifMain,
      };
      await rjStore.assignTaskRepairer(userStore.user.LoginName, setPara);
    }
    setAssigning(false);
    if (!didUnmount) {
      navigation.goBack();
    }
  };
  const groupSelUsers = [];
  const groupNum = 4;
  const selUserGroups = Math.ceil(selectedUsers.length / groupNum);
  for (let i = 0; i < selUserGroups; i += 1) {
    groupSelUsers.push(selectedUsers.slice(i * groupNum, (i + 1) * groupNum));
  }
  const memoizedItem = useMemo(
    () => ({ item }) => (
      <MemoizedRenderItem item={item} onUserCheck={handleUserCheck} />
    ),
    [],
  );
  return (
    <>
      <LoadingContainer
        onRefresh={userStore.getFlightWorkerUsers}
        loading={userStore.getFlightWorkerUsers.loading}
        header={
          <List>
            <Flex>
              <Flex.Item flex={9}>
                <Picker
                  data={userStore.flightWorkers.departments}
                  cols={2}
                  format={(vals) => vals.filter((v) => v).join('/')}
                  value={deptPicks}
                  onOk={handleDeptPick}
                >
                  <List.Item>部门过滤</List.Item>
                </Picker>
              </Flex.Item>
              {!!deptPicks.length && (
                <Flex.Item flex={1}>
                  <TouchableOpacity onPress={() => handleDeptPick([])}>
                    <IconX origin="ant" name="closecircleo" />
                  </TouchableOpacity>
                </Flex.Item>
              )}
            </Flex>
            <SearchBar
              placeholder="请输入姓名"
              value={searchVal}
              onCancel={handleSearchCancel}
              onChange={handleSearchChange}
              style={styles.searchbarSty}
            />
            <List.Item
              extra={
                groupSelUsers.length === 0 && (
                  <Flex>
                    <Flex.Item />
                    <Tag selected>暂无数据</Tag>
                  </Flex>
                )
              }
            >
              已选择人员
            </List.Item>
            {groupSelUsers.map((gsulist) => (
              <Flex key={gsulist[0].id}>
                <Flex.Item />
                {gsulist.map((slu) => (
                  <ClosableTag
                    key={slu.id}
                    onClose={() => handleUserCheck({ ...slu, checked: false })}
                    userStyle={{
                      tag: { marginHorizontal: 15, marginVertical: 10 },
                    }}
                  >
                    {slu.name}
                  </ClosableTag>
                ))}
              </Flex>
            ))}
          </List>
        }
        data={userStore.flightWorkers.workers.filter(
          (wkr) =>
            !(searchVal && wkr.name.indexOf(searchVal) === -1) &&
            !(
              deptPicks.length > 0 &&
              deptPicks[deptPicks.length - 1] !== wkr.teamCode
            ),
        )}
        renderItem={memoizedItem}
      />
      <Button
        type="primary"
        onPress={handleUserAssign}
        loading={userStore.getFlightWorkerUsers.loading || assigning}
      >
        确认
      </Button>
    </>
  );
}

WorkerUserSelectPage.routeName = 'WorkerUserSelect';
WorkerUserSelectPage.permission = 'RWorkerUserSelect';
export default WorkerUserSelectPage;
